<template>
  <div class="book-create">
    <el-card class="box-card">
      <h2 class="form-title">创建新书籍</h2>
      <el-form ref="bookForm" :model="bookData" label-width="100px">
        <!-- 封面图片上传 -->
        <el-form-item label="封面图片" class="form-item">
          <el-upload class="avatar-uploader" accept="image/*" :show-file-list="false"
            :before-upload="beforeAvatarUpload" :on-change="handleFileChange">
            <img v-if="bookCoverPreview" :src="bookCoverPreview" class="avatar" />
            <div v-else class="upload-placeholder">
              <i class="el-icon-plus avatar-uploader-icon"></i>
              <span>上传封面</span>
            </div>
          </el-upload>
        </el-form-item>

        <!-- 书名输入 -->
        <el-form-item label="书名" class="form-item">
          <el-input v-model="bookData.name" placeholder="请输入书名"></el-input>
        </el-form-item>

        <!-- 作者输入 -->
        <el-form-item label="作者" class="form-item">
          <el-input v-model="bookData.author" placeholder="请输入作者"></el-input>
        </el-form-item>

        <!-- 描述输入 -->
        <el-form-item label="描述" class="form-item">
          <el-input v-model="bookData.description" placeholder="请输入描述内容（可选）"></el-input>
        </el-form-item>

        <!-- 类别选择 -->
        <el-form-item label="类别" class="form-item">
          <el-select v-model="bookData.category_id" placeholder="请选择类别">
            <el-option v-for="category in categories" :key="category.ID" :label="category.Name"
              :value="category.ID"></el-option>
          </el-select>
        </el-form-item>

        <!-- 学院多选 -->
        <el-form-item label="学院" class="form-item">
          <el-select v-model="bookData.selectedColleges" multiple placeholder="请选择学院（可多选）">
            <el-option v-for="college in colleges" :key="college.id" :label="college.name"
              :value="college.id"></el-option>
          </el-select>
        </el-form-item>

        <!-- 学期选择 -->
        <el-form-item label="学期" class="form-item">
          <el-select v-model="bookData.semester" placeholder="请选择学期">
            <el-option v-for="semester in semesters" :key="semester.id" :label="semester.name"
              :value="semester.id"></el-option>
          </el-select>
        </el-form-item>

        <!-- 价格输入 -->
        <el-form-item label="价格" class="form-item">
          <el-input v-model="bookData.price" placeholder="请输入价格" type="number"></el-input>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item class="submit-item">
          <el-button type="primary" @click="createNewBook" size="large" class="submit-btn">
            创建新书
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <div class="book-query">
    <h2>图书查询</h2>
    <div class="query-form">
      <el-row gutter="20" type="flex" justify="center">
        <el-col :span="8">
          <el-form-item label="学院">
            <el-select v-model="selectedCollege" placeholder="请选择学院">
              <el-option v-for="college in colleges" :key="college.id" :label="college.name"
                :value="college.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学期">
            <el-select v-model="selectedSemester" placeholder="请选择学期">
              <el-option v-for="semester in semesters" :key="semester.id" :label="semester.name"
                :value="semester.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" @click="fetchBooksByCollegeAndSemester">查询图书</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
  </div>


  <!-- 图书列表显示 -->
  <div v-if="books.length > 0" class="book-list">
    <h3>查询结果</h3>
    <table>
      <thead>
        <tr>
          <th>书名</th>
          <th>作者</th>
          <th>描述</th>
          <th>价格</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="book in books" :key="book.id">
          <td>{{ book.name }}</td>
          <td>{{ book.author }}</td>
          <td>{{ book.description }}</td>
          <td>{{ book.price }} 元</td>
          <td>
            <el-button type="danger" size="small" @click="deleteBook(book.id)">删除</el-button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
  <div v-else class="no-data-container">
    <p>暂无数据</p>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { fetchColleges, fetchSemesters, fetchBooks } from "@/api/api";

export default {
  name: 'BookCreate',
  setup() {
    const bookCover = ref(null);
    const bookCoverPreview = ref(null);
    const categories = ref([]);
    const colleges = ref([]);
    const semesters = ref([]);
    const bookData = reactive({
      name: '',
      author: '',
      category_id: '',
      cover_image_id: '',
      price: '',
      selectedColleges: [],
      semester: '',
      description: '暂无描述',
    });
    const books = ref([]); // 存储查询到的图书列表
    const selectedCollege = ref(null); // 选中的学院ID
    const selectedSemester = ref(null); // 选中的学期ID

    const handleFileChange = (file) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        bookCoverPreview.value = e.target.result;
      };
      reader.readAsDataURL(file.raw);
      bookCover.value = file.raw;
    };

    const beforeAvatarUpload = (file) => {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        ElMessage.error('上传的文件必须是图片格式!');
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    };

    const createNewBook = async () => {
      if (!bookCover.value) {
        ElMessage.error('请先上传封面图片');
        return;
      }
      if (!bookData.name || !bookData.author || !bookData.category_id || !bookData.price) {
        ElMessage.error('请填写所有必填项');
        return;
      }

      try {
        const formData = new FormData();
        formData.append('file', bookCover.value);
        const response = await axios.post('/api/v1/cover_img/create', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        });

        if (response.data && response.data.data && response.data.data.id) {
          bookData.cover_image_id = response.data.data.id;
        } else {
          throw new Error('封面图片上传成功,但未获取到图片ID');
        }

        bookData.applicable_college_ids = bookData.selectedColleges.join(',');
        bookData.applicable_semester_id = bookData.semester;

        const bookResponse = await axios.post('/api/v1/learning_material/create', {
          name: bookData.name,
          author: bookData.author,
          price: parseInt(bookData.price, 10),
          category_id: bookData.category_id,
          cover_image_id: bookData.cover_image_id,
          applicable_college_ids: bookData.applicable_college_ids,
          applicable_semester_id: bookData.applicable_semester_id,
          description: bookData.description,
        });

        ElMessage.success('书籍创建成功');
        console.log('书籍创建成功:', bookResponse.data);
        // 清空表单
        bookData.name = '';
        bookData.author = '';
        bookData.description = '暂无描述';
        bookData.category_id = '';
        bookData.cover_image_id = '';
        bookData.price = '';
        bookData.selectedColleges = [];
        bookData.semester = '';
        bookCover.value = null; // 清空已上传的文件
        bookCoverPreview.value = null; // 清空文件预览
      } catch (error) {
        ElMessage.error('创建书籍失败');
        console.error('创建书籍失败:', error);
      }
    };

    const fetchBooksByCollegeAndSemester = async () => {
      if (!selectedCollege.value || !selectedSemester.value) {
        ElMessage.warning('请选择学院和学期');
        return;
      }

      try {
        const response = await fetchBooks();

        if (response.data && response.data.data) {
          // 过滤图书，使得applicable_semester_id字段与选择的学期相同，并且applicable_college_ids包含选择的学院ID
          books.value = response.data.data.filter(book =>
            book.applicable_semester_id.toString() === selectedSemester.value.toString() &&
            book.applicable_college_ids.split(',').includes(selectedCollege.value.toString())
          );
          ElMessage.success('图书查询成功');
        } else {
          ElMessage.error('图书查询失败');
        }
      } catch (error) {
        ElMessage.error('网络错误，无法查询图书');
      }
    };
    
    const deleteBook = async (bookId) => {
      try {
        const response = await axios.post(`/api/v1/learning_material/delete`, { id: bookId });
        if (response.data.code === 200) {
          ElMessage.success('书籍删除成功');
          // 删除成功后，重新查询书籍列表以更新UI
          fetchBooksByCollegeAndSemester();
        } else {
          ElMessage.error('书籍删除失败: ' + response.data.msg);
        }
      } catch (error) {
        ElMessage.error('删除书籍时发生错误');
        console.error('删除书籍失败:', error);
      }
    };

    onMounted(async () => {
      try {
        const response = await axios.get('/api/v1/learning_material_category/list');
        categories.value = response.data.data;

        const collegesResponse = await fetchColleges();
        colleges.value = collegesResponse;

        const semestersResponse = await fetchSemesters();
        semesters.value = semestersResponse;
      } catch (error) {
        ElMessage.error('获取数据失败');
        console.error('获取数据失败:', error);
      }
    });

    return {
      bookCover,
      bookCoverPreview,
      categories,
      colleges,
      semesters,
      bookData,
      handleFileChange,
      beforeAvatarUpload,
      createNewBook,
      books,
      selectedCollege,
      selectedSemester,
      fetchBooksByCollegeAndSemester,
      deleteBook
    };
  },
};
</script>

<style scoped>
.book-create {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
}

.form-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 20px;
}

.upload-placeholder {
  text-align: center;
  color: #8c939d;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.avatar-uploader-icon {
  font-size: 28px;
}

.avatar {
  width: 178px;
  height: 178px;
  border-radius: 6px;
  object-fit: cover;
}

.el-form-item {
  margin-bottom: 20px;
}

.submit-item {
  text-align: center;
}

.submit-btn {
  width: 100%;
  height: 50px;
  font-size: 18px;
}

.el-input,
.el-select {
  width: 100%;
}

.box-card {
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.query-form {
  margin-top: 20px;
}

.book-list {
  margin-top: 20px;
}

.no-data-container {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.book-query {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 60px;
}

.query-form {
  width: 80%;
  text-align: center;
}
</style>
